<template>
  <div class="log-detail-container">
    <div v-loading="loading" class="detail-content">
      <!-- 基本信息 -->
      <el-card class="detail-card" shadow="hover">
        <div slot="header">
          <span><i class="el-icon-info"></i> 基本信息</span>
        </div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="日志ID">{{ logDetail.logId }}</el-descriptions-item>
          <el-descriptions-item label="上传时间">{{ parseTime(logDetail.uploadTime) }}</el-descriptions-item>
          <el-descriptions-item label="定位器编码">
            <el-link type="primary" @click="handleLocatorDetail">{{ logDetail.locatorCode }}</el-link>
          </el-descriptions-item>
          <el-descriptions-item label="器具编码">
            <el-link type="success" @click="handleContainerDetail" v-if="logDetail.containerCode">{{ logDetail.containerCode }}</el-link>
            <span v-else class="text-muted">未绑定</span>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ parseTime(logDetail.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ parseTime(logDetail.updateTime) }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 位置信息 -->
      <el-card class="detail-card" shadow="hover">
        <div slot="header">
          <span><i class="el-icon-location"></i> 位置信息</span>
        </div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="经度">{{ logDetail.longitude }}</el-descriptions-item>
          <el-descriptions-item label="纬度">{{ logDetail.latitude }}</el-descriptions-item>
          <el-descriptions-item label="详细地址" :span="2">
            {{ logDetail.uploadAddress || '暂无地址信息' }}
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 地图显示 -->
        <div class="map-container" style="height: 300px; margin-top: 20px;">
          <div id="detailMap" style="width: 100%; height: 100%;"></div>
        </div>
      </el-card>

      <!-- 传感器数据 -->
      <el-card class="detail-card" shadow="hover">
        <div slot="header">
          <span><i class="el-icon-cpu"></i> 传感器数据</span>
        </div>
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="sensor-item">
              <div class="sensor-label">电池电量</div>
              <div class="sensor-value">
                <el-progress
                  :percentage="logDetail.batteryLevel"
                  :color="getBatteryColor(logDetail.batteryLevel)"
                  :stroke-width="15"
                />
                <span class="sensor-text">{{ logDetail.batteryLevel }}%</span>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="sensor-item">
              <div class="sensor-label">温度</div>
              <div class="sensor-value">
                <span class="sensor-number" :class="getTemperatureClass(logDetail.temperature)">
                  {{ logDetail.temperature }}°C
                </span>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="sensor-item">
              <div class="sensor-label">湿度</div>
              <div class="sensor-value">
                <span class="sensor-number">{{ logDetail.humidity }}%</span>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="sensor-item">
              <div class="sensor-label">震动等级</div>
              <div class="sensor-value">
                <el-tag :type="getShockLevelType(logDetail.shockLevel)">
                  {{ getShockLevelText(logDetail.shockLevel) }}
                </el-tag>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 其他数据 -->
      <el-card class="detail-card" shadow="hover" v-if="otherData">
        <div slot="header">
          <span><i class="el-icon-data-analysis"></i> 其他数据</span>
        </div>
        <el-descriptions :column="3" border>
          <el-descriptions-item 
            v-for="(value, key) in otherData" 
            :key="key"
            :label="getOtherDataLabel(key)"
          >
            {{ value }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 关联信息 -->
      <el-card class="detail-card" shadow="hover" v-if="logDetail.locatorInfo || logDetail.containerInfo">
        <div slot="header">
          <span><i class="el-icon-link"></i> 关联信息</span>
        </div>
        <el-tabs type="border-card">
          <el-tab-pane label="定位器信息" v-if="logDetail.locatorInfo">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="定位器编码">{{ logDetail.locatorInfo.locatorCode }}</el-descriptions-item>
              <el-descriptions-item label="设备型号">{{ logDetail.locatorInfo.deviceModel }}</el-descriptions-item>
              <el-descriptions-item label="生产日期">{{ parseTime(logDetail.locatorInfo.manufactureDate, '{y}-{m}-{d}') }}</el-descriptions-item>
              <el-descriptions-item label="设备状态">
                <dict-tag :options="dict.type.pack_locator_status" :value="logDetail.locatorInfo.locatorStatus"/>
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          <el-tab-pane label="器具信息" v-if="logDetail.containerInfo">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="器具编码">{{ logDetail.containerInfo.containerCode }}</el-descriptions-item>
              <el-descriptions-item label="器具型号">{{ logDetail.containerInfo.materialCode }}</el-descriptions-item>
              <el-descriptions-item label="型号名称">{{ logDetail.containerInfo.materialName }}</el-descriptions-item>
              <el-descriptions-item label="当前仓库">{{ logDetail.containerInfo.currentWarehouseName }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getLocationLog } from "@/api/pack/locationLog";
import { getDicts } from "@/api/system/dict/data";

export default {
  name: "LogDetail",
  dicts: ['pack_locator_status'],
  props: {
    logId: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      logDetail: {},
      map: null
    };
  },
  computed: {
    otherData() {
      try {
        if (this.logDetail.otherData) {
          return typeof this.logDetail.otherData === 'string' 
            ? JSON.parse(this.logDetail.otherData) 
            : this.logDetail.otherData;
        }
        return null;
      } catch (e) {
        return null;
      }
    }
  },
  created() {
    this.getDetail();
  },
  methods: {
    getDetail() {
      this.loading = true;
      getLocationLog(this.logId).then(response => {
        this.logDetail = response.data;
        this.loading = false;
        
        // 初始化地图（延迟执行，确保DOM已渲染）
        this.$nextTick(() => {
          this.initMap();
        });
      });
    },
    
    initMap() {
      // 检查是否有经纬度数据
      if (!this.logDetail.latitude || !this.logDetail.longitude) {
        return;
      }
      
      // 加载高德地图脚本（如果未加载）
      this.loadMapScript().then(() => {
        // 创建地图实例
        this.map = new AMap.Map('detailMap', {
          zoom: 15,
          center: [this.logDetail.longitude, this.logDetail.latitude]
        });
        
        // 添加标记点
        const marker = new AMap.Marker({
          position: [this.logDetail.longitude, this.logDetail.latitude],
          title: this.logDetail.locatorCode
        });
        
        this.map.add(marker);
      });
    },
    
    loadMapScript() {
      // 使用map-utils.js中的loadAMapScript方法
      return import('@/components/MapContainer/map-utils').then(module => {
        return module.loadAMapScript();
      });
    },
    
    // 获取电池颜色
    getBatteryColor(level) {
      if (level >= 80) return '#67c23a';
      if (level >= 50) return '#e6a23c';
      if (level >= 20) return '#f56c6c';
      return '#909399';
    },
    
    // 获取温度样式类
    getTemperatureClass(temp) {
      if (temp < 0) return 'temp-cold';
      if (temp > 35) return 'temp-hot';
      return 'temp-normal';
    },
    
    // 获取震动等级类型
    getShockLevelType(level) {
      const types = ['', 'success', 'info', 'warning', 'danger', 'danger'];
      return types[level] || 'info';
    },
    
    // 获取震动等级文本
    getShockLevelText(level) {
      const texts = ['', '轻微', '一般', '中等', '强烈', '剧烈'];
      return texts[level] || '未知';
    },
    
    // 获取其他数据字段标签
    getOtherDataLabel(key) {
      const labelMap = {
        signal: '信号强度',
        gpsAccuracy: 'GPS精度',
        speed: '速度',
        satellites: '卫星数量',
        hdop: '水平精度',
        altitude: '海拔高度'
      };
      return labelMap[key] || key;
    },
    
    // 定位器详情
    handleLocatorDetail() {
      const { locatorId } = this.logDetail;
      if (locatorId) {
        this.$router.push({ path: '/pack/locator', query: { locatorId } });
      }
    },
    
    // 器具详情
    handleContainerDetail() {
      const { containerId } = this.logDetail;
      if (containerId) {
        this.$router.push({ path: '/pack/container', query: { containerId } });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.log-detail-container {
  padding: 20px;
  
  .detail-card {
    margin-bottom: 20px;
  }
  
  .sensor-item {
    text-align: center;
    padding: 20px;
    
    .sensor-label {
      font-size: 14px;
      color: #666;
      margin-bottom: 10px;
    }
    
    .sensor-value {
      .sensor-number {
        font-size: 24px;
        font-weight: bold;
      }
      
      .sensor-text {
        font-size: 14px;
        color: #666;
        margin-left: 10px;
      }
    }
  }
  
  .map-container {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
  }
  
  .temp-cold {
    color: #409eff;
  }
  
  .temp-normal {
    color: #67c23a;
  }
  
  .temp-hot {
    color: #f56c6c;
  }
  
  .text-muted {
    color: #c0c4cc;
  }
}
</style> 